//
//  NSArray+Honda.m
//  Honda
//
//  Created by Wang.Xinlei on 4/9/13.
//  Copyright (c) 2013 HeninHoo. All rights reserved.
//

#import "NSArray+Honda.h"

@implementation NSArray (Honda)

+ (BOOL)validArray:(NSArray *)array {
    return ([self valid:array] && 0 < array.count);
}

+ (BOOL)invalidArray:(NSArray *)array {
    return ([self invalid:array] || 0 == array.count);
}

+ (NSArray *)arrayWithArrayOrNil:(NSArray *)arrayOrNil {
    return [[[self alloc] initWithArrayOrNil:arrayOrNil] autorelease];
}

- (id)initWithArrayOrNil:(NSArray *)arrayOrNil {
    if ([NSArray invalid:arrayOrNil]) {
        return [self initWithArray:arrayOrNil];
    }
    else {
        return [self init];
    }
}

- (id)firstObject {
    return [self nilOrObjectAtIndex:0];
}

- (id)nilOrObjectAtIndex:(NSUInteger)index {
    if (0 < self.count && index < self.count) {
        return [self objectAtIndex:index];
    }
    
    return nil;
}

@end


@implementation NSMutableArray (Honda)

- (void)addNilOrObject:(id)anObject {
    if ([NSObject valid:anObject]) {
        [self addObject:anObject];
    }
}

- (void)addUniqueObject:(id)anObject {
    if ([NSObject valid:anObject] && ! [self containsObject:anObject]) {
        [self addObject:anObject];
    }
}

- (void)insertNilOrObject:(id)anObject atIndex:(NSUInteger)index {
    if ([NSObject valid:anObject] && index < self.count) {
        [self insertObject:anObject atIndex:index];
    }
}

- (void)insertUniqueObject:(id)anObject atIndex:(NSUInteger)index {
    if ([NSObject valid:anObject] && index < self.count) {
        NSUInteger find = [self indexOfObject:anObject];
        [self insertObject:anObject atIndex:index];
        if (NSNotFound != find && find != index) {
            [self removeObjectAtIndex:find];
        }
    }
}

@end
